package com.zhangmeng.tools.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import com.zhangmeng.tools.utils.AlertUtils;
import com.zhangmeng.tools.utils.ImagePath;
import javafx.beans.property.SimpleObjectProperty;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.HashMap;

/**
 * @author : 芊芊墨客
 * @version : 1.0
 * @date : 2023-03-08 12:00
 */
@Slf4j
public class HttpUploadController {

    @FXML
    public Button upload_button;

    @FXML
    public Button choose_file_button;

    @FXML
    public TextArea upload_result;

    @FXML
    public TextField url;

    @FXML
    private TextField file_path;

    private final SimpleObjectProperty<File> file_vale = new SimpleObjectProperty<>();

    @FXML
    public void initialize() {

        upload_result.setWrapText(true);

        choose_file_button.setText(null);
        ImageView iv = new ImageView(new Image(ImagePath.path(ImagePath.ImagePathType.IMAGE_FILE)));
        iv.setPreserveRatio(true);
        iv.setFitWidth(18);
        choose_file_button.setGraphic(iv);

        choose_file_button.setOnAction(event -> {
            Stage stage = new Stage();
            FileChooser fc = new FileChooser();
            fc.setTitle("单选文件");
            fc.getExtensionFilters().addAll(
                    new FileChooser.ExtensionFilter("所有类型", "*.*")
            );

            File file = fc.showOpenDialog(stage);
            if (file == null) {
                return;
            }
            file_path.setText(file.getAbsolutePath());
            file_vale.setValue(file);
        });

        upload_button.setOnAction(event -> {

            if (url.getText().length() == 0){
                AlertUtils.alert_warning("请输入上传接口再试!");
                return;
            }

            HashMap<String, Object> paramMap = new HashMap<>();
            //文件上传只需将参数中的键指定（默认file），值设为文件对象即可，对于使用者来说，文件上传与普通表单提交并无区别

            if (file_vale.getValue() == null){
                AlertUtils.alert_warning("请选择文件后再试!");
                return;
            }

            paramMap.put("file", file_vale.getValue());

            String result= HttpUtil.post(url.getText(), paramMap);
            upload_result.setText(result);
        });

    }
}
